/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package auth

import (
	chttp "did-service/common/http"
	"did-service/common/jwt"
	"did-service/config"
	"did-service/plugins/sessionmgr"
	"net/http"

	"github.com/emicklei/go-restful"
)

func AuthFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	ret, payload, _ := jwt.ValidateToken(req.Request)
	useSession := config.GetBool("did.auth.use-session")

	if ret && (!useSession || sessionmgr.Get().Check(payload.WalletId, req.Request)) {
		req.SetAttribute("CUR_WALLET", payload)
		req.SetAttribute("CUR_WALLET_ID", payload.WalletId)
		req.SetAttribute("CUR_USER_NAME", payload.UserName)
		req.SetAttribute("CUR_NICK_NAME", payload.NickName)
		req.SetAttribute("CUR_USER_TYPE", payload.UserType)
		chain.ProcessFilter(req, resp)
	} else {
		// validate failed
		chttp.FailedWithStatus(resp, http.StatusUnauthorized, "认证失败")
		return
	}
}

func GetCurrentWalletId(req *restful.Request) string {
	walletId := req.Attribute("CUR_WALLET_ID")
	return walletId.(string)
}

func GetCurrentUserType(req *restful.Request) string {
	userType := req.Attribute("CUR_USER_TYPE")
	return userType.(string)
}

func GetCurrentUserName(req *restful.Request) string {
	userName := req.Attribute("CUR_USER_NAME")
	return userName.(string)
}

func GetCurrentNickName(req *restful.Request) string {
	nickName := req.Attribute("CUR_NICK_NAME")
	return nickName.(string)
}
